import {createStore, applyMiddleware} from './my-redux'
import { Provider, connect } from './my-react-redux'
import thunk from './my-redux-thunk'
import arrayThunk from './redux-array'
import React from 'react'
import ReactDOM from 'react-dom'

// reducer
function counter(state = 100, action) {
  switch (action.type) {
    case 'add':
      return state + 1
    case 'cut':
      return state - 1
    default:
      return state
  }
}

const store = createStore(counter, applyMiddleware(thunk, arrayThunk))

class App extends React.Component {
  render () {
    // console.log(this.props)
    return (
      <div>
        <h1>{this.props.num}</h1>
        <button onClick={() => this.props.addNum()}>+ 1</button>
        <button onClick={() => this.props.cutNum()}>- 1</button>
        <button onClick={() => this.props.twice()}>+ 两次</button>
        <button onClick={() => this.props.asyncAddNum()}>异步+ 1</button>
      </div>
    )
  }
}

let addNum = function () {
  return { type: 'add' }
}
let cutNum = function () {
  return { type: 'cut' }
}
// thunk 中间件
let asyncAddNum = function () {
  return dispatch => {
    setTimeout(() => {
      dispatch({type: 'add'})
    }, 3000)
  }
}
// arrayThunk 中间件
let twice = function () {
  return [
    {type: 'add'},
    {type: 'add'},
    asyncAddNum()
  ]
}

let mapStateToProps = state => ({num: state})
let mapDispatchToProps = {addNum, cutNum, asyncAddNum, twice}

App = connect(mapStateToProps, mapDispatchToProps)(App)

ReactDOM.render(
  <Provider store={store}>
    <App test={222}/>
  </Provider>
  , document.getElementById('root'))
